#! python3
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''

import binascii
import struct
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
import modbus_tk.defines as cst
import modbus_tk.modbus_rtu as modbus_rtu
import modbus_tk.modbus_tcp as modbus_tcp
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.plugins.A01_T5GH04 import A01_Para
from com.zxy.z_debug import z_debug
class A01_T5GH04_MODBUS(z_debug):
    def __init__(self):
        pass
    def _getCrc16(self,RtuStr):
        b = 0xA001
        a = 0xFFFF
        for byte in RtuStr:
            a = a ^ byte
            for i in range(8):
                if a & 0x0001:
                    a = a >> 1
                    a = a ^ b 
                else:
                    a = a >> 1
        aa = '0' * (6 - len(hex(a))) + hex(a)[2:]
        lo, hh = int(aa[:2], 16), int(aa[2:], 16)
        hexbytes = bytes([hh, lo])
        return hexbytes
    def get_data_com(self,inputComPort,CmdStr):         
        try:  
            com_at = Com_Fun.GetHashTable(Com_Para.htComPort,inputComPort)  
            inputByte  = bytes().fromhex(CmdStr)
            inputByte = inputByte+self._getCrc16(inputByte)
            strFG = str(binascii.b2a_hex(inputByte))[2:-1]
            if com_at.WritePortData(inputByte) > 0:
                comValue = com_at.attReturnValue
                if comValue is None:
                    print("com port not data return")
                    return None
                temReturn = str(binascii.b2a_hex(comValue))[2:-1]                 
                temReturn = " ".join([temReturn[e:e+2] for e in range(0,len(temReturn),2)])                    
                com_at.attReturnValue = None
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            Data = -1
        return Data 
    def get_data_rtu(self,inputComPort,inputModbusAddr,inputModbusBegin,inputModbusLength):
        red = []
        try:
            com_at = Com_Fun.GetHashTable(Com_Para.htComPort,inputComPort)
            print("a1:"+inputComPort)
            master = modbus_rtu.RtuMaster(com_at.attSerial)    
            print("a2:")                     
            master.set_timeout(5.0)
            master.set_verbose(True)
            print("a3:")  
            red = master.execute(inputModbusAddr, cst.READ_HOLDING_REGISTERS, inputModbusBegin, inputModbusLength)  # 这里可以修改需要读取的功能码
            print("modbus_rtu Result:"+str(red))
            return list(red)
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
            return red
    def ReadFloat(self,n1,n2,reverse=False):
        n = '%04x'%n1
        m = '%04x'%n2
        if reverse:
            v = n + m
        else:
            v = m + n
        y_bytes = bytes.fromhex(v)
        y = struct.unpack('!f',y_bytes)[0]
        y = round(y,2)
        return y
    def WriteFloat(self,value,reverse=False):
        y_bytes = struct.pack('!f',value)
        y_hex = ''.join(['%02x' % i for i in y_bytes])
        n,m = y_hex[:-4],y_hex[-4:]
        n,m = int(n,16),int(m,16)
        if reverse:
            v = [n,m]
        else:
            v = [m,n]
        return v
    def ReadDint(self,*args,reverse=False):
        for n,m in args:
            n,m = '%04x'%n,'%04x'%m
        if reverse:
            v = n + m
        else:
            v = m + n
        y_bytes = bytes.fromhex(v)
        y = struct.unpack('!i',y_bytes)[0]
        return y
    def WriteDint(self,value,reverse=False):
        y_bytes = struct.pack('!i',value)
        y_hex = ''.join(['%02x' % i for i in y_bytes])
        n,m = y_hex[:-4],y_hex[-4:]
        n,m = int(n,16),int(m,16)
        if reverse:
            v = [n,m]
        else:
            v = [m,n]
        return v         